import 'package:easy_refresh/easy_refresh.dart';
import 'package:get/get.dart';

import 'package:package_info_plus/package_info_plus.dart';
import 'package:ball_lion/base/base_controller.dart';
import 'package:ball_lion/entity/other/resource_entity.dart';
import 'package:ball_lion/entity/other/app_update_entity.dart';
import 'package:ball_lion/entity/pay/my_coupon.dart';
import 'package:ball_lion/module/mine/my_web_page.dart';
import 'package:ball_lion/module/mine/my_aboutus_page.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/service/resource_service.dart';
import 'package:ball_lion/server/api/other_api.dart';
import 'package:ball_lion/server/api/pay_api.dart';
import 'package:ball_lion/server/api/user_api.dart';
import 'package:ball_lion/utils/sp_utils.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/widgets/base/wqs_dialog.dart';

class MyPageLogic extends BaseController {
  final EasyRefreshController refreshC = EasyRefreshController();
  bool _onRefresh = false;
  List<MyCouponEntity>? _coupons;
  List<ResourceEntity>? activeMenu;
  AppUpdateEntity? versionInfo;
  bool hasNewVersion = false;

  bool get onRefresh => _onRefresh;
  List<MyCouponEntity>? get coupons => _coupons;

  set coupons(List<MyCouponEntity>? value) {
    _coupons = value;
    update();
  }

  set onRefresh(bool value) {
    _onRefresh = value;
    update();
  }

  @override
  void onInit() {
    super.onInit();
    checkVersion();
  }

  @override
  void onReady() async {
    super.onReady();
    getMenu();
    getCoupon();
  }

  Future getCoupon() async {
    if (User.isLogin) {
      coupons = await PayApi.myCoupons() ?? [];
    } else {
      coupons = [];
    }
  }

  Future getMenu() async {
    var list = await OtherApi.getAppList("app_my_item");
    activeMenu = list?.where((element) => element.button == "my_item").toList();
    update();
  }

  Future getData() async {
    await User.fetchUserInfo();
    if (User.isLogin) {
      coupons = await PayApi.myCoupons() ?? [];
    }
    update();
  }

  void doRefresh() {
    if (refreshC.headerState?.mode.isIdle == false) return;
    refreshC.callRefresh();
  }

  tapMyCollection() {
    Utils.onEvent("my_collection");
    User.needLogin(() => Get.toNamed(Routes.myCollection));
  }

  tapMyFocus() {
    Utils.onEvent("my_follow");
    User.needLogin(() => Get.toNamed(Routes.myFocus));
  }

  tapExpert() {
    Utils.onEvent("my_expert_joinin");
    User.needLogin(() => Get.toNamed(Routes.expertRequestType));
  }

  // tapShare() => Utils.share();
  tapContact() {
    Utils.onEvent("my_custom_service");
    Get.toNamed(Routes.myContact);
  }

  tapPushSetting() {
    Utils.onEvent("tssz");
    Get.toNamed(Routes.myPushSetting);
  }

  tapSettings() {
    Utils.onEvent("my_settings");
    if (hasNewVersion) {
      SpUtils.versionIgnore = versionInfo?.latestVersion;
    }
    checkVersion();
    Get.toNamed(Routes.mySetting);
  }

  tapLive() async {
    Utils.onEvent("zjzb");
    if (User.isPersonVerified) {
      Get.toNamed(Routes.expertRooms);
    } else {
      Get.dialog(
              const QsDialog.alert("实名认证",
                  content: "根据《互联网信息服务管理办法》，直播需要实名认证哦", confirmText: "立即认证"),
              barrierDismissible: false)
          .then((value) {
        if (value is bool && value) {
          Get.toNamed(Routes.accountVerify);
        }
      });
    }
  }

  tapRecharge({bool coin = false}) {
    Utils.onEvent(coin ? "my_coin" : 'my_charge');
    User.needLogin(
      () async {
        await Get.toNamed(Routes.myRecharge);
        update();
      },
    );
  }

  tapVip() {
    Utils.onEvent('my_vip_open');
    Get.toNamed(Routes.vipCenter);
  }

  tapPurchase() {
    Utils.onEvent("my_order");
    User.needLogin(() => Get.toNamed(Routes.myPurchase), fail: Get.back);
  }

  tapCoupons() {
    Utils.onEvent("my_coupon");
    User.needLogin(() => Get.toNamed(Routes.myCoupons), fail: Get.back);
  }

  tapQuestion() {
    Utils.onEvent("my_feedback");
    Get.toNamed(Routes.help);
  }

  tapAboutUs() => Get.to(const MyAboutUsPage());

  tapUserInfo() => User.needLogin(() => Get.toNamed(Routes.myEditInfo));

  tapHeaderName() async {
    if (User.isLogin) {
      // Get.toNamed(Routes.userPage,
      //     arguments: User.info?.id, parameters: {'type': '1'});
    } else {
      await Utils.login();
    }
  }

  tapTask() {
    Utils.onEvent("my_signin");
    User.needLogin(() => Get.toNamed(Routes.homeTask));
  }

  tapShare() async {
    if (SpUtils.shareClick == false) SpUtils.shareClick = true;
    List<ResourceEntity>? list = await OtherApi.getAppList("fxlb");
    String url = list?.firstWhere((e) => e.button == "邀请页链接").content ?? "";
    if (url.noValue) return;
    Get.toNamed(Routes.webview, arguments: WebPara(url, title: "邀请得球币"));
  }

  void getMyCoupon() async {
    if (User.isLogin) {
      await UserApi.joinActivity('invite1');
      Get.find<ResourceService>().getAppLoginConfig().then((value) {
        update();
      });
    }
  }

  Future checkVersion() async {
    PackageInfo.fromPlatform().then((value) async {
      versionInfo = await OtherApi.checkUpdate(value.version);
      hasNewVersion = (versionInfo?.needUpdate ?? 0) > 0 &&
          versionInfo?.latestVersion != SpUtils.versionIgnore;
      update();
    });
  }

  @override
  void getRefresh() async {
    onRefresh = true;
    await User.fetchUserInfo();
    if (User.isLogin) {
      coupons = await PayApi.myCoupons() ?? [];
    }
    update();
    onRefresh = false;
    super.getRefresh();
  }
}
